/**
 * @description 异步页面组件
 * @name ajaxComponent
 * @emits emit-back(data) 组件回调函数，data的格式为 { emit: 'xxx', data: { ... } }
 * @props data 页面参数
 * @props appendBody 是否在body中追加
 * @props url 页面地址
 */
((window)=>{

  window.setComponent({
    name:'ajax-component',
    emits: ['emit-back'],
    props: {
      appendBody: {
        type: Boolean,
        default: false
      },
      url: {
        type: String,
        default: ''
      },
      data: {
        type: [Object, Array],
        default: () => {
          return {}
        }
      }
    },
    data() {
      const fn_guid = window.guid || $ktl.guid;
      if (fn_guid) {
        let ajaxId = 'ajax_' + fn_guid().replace(/-/g, '');
        return {
          ajaxId
        }
      }
      return {}
    },
    render(createElement){
      // 如果是追加到body
      if(this.appendBody){
        return ""
      }

      // 注册 Vue3 组件
      if (Vue.version.startsWith('3')) {
        const { h } = Vue;
        return h('div', {
          id: this.ajaxId,
          class: {
            'ajax-component': true
          }
        })
      }
      // 注册 Vue2 全局组件
      else if (Vue.version.startsWith('2')) {
        return createElement('div', {
          attrs: {
            id: this.ajaxId,
          },
          class: 'ajax-component'
        })
      }

      return ""
    },
    mounted(){
      console.log("data", this.data);
      
      if (!window.$bus) {
				window.$bus = BusMessage.init();
      }

      // 消息订阅：参数传递
      window.$bus.subscribe(this.ajaxId, (payload) => {
        this.$emit("emit-back", payload)
      }, "emit")

      // 消息订阅：参数传递
      window.$bus.subscribe(this.ajaxId, callback => {
        callback && callback(this.data)
      }, "data")

      if(this.url){
        $.ajax({
          url: this.url + (this.url.indexOf("?") > 0 ? '&' : '?') + `ajaxId=${this.ajaxId}`,
          success: (code) => {
            // 加载内容组件
            this.$nextTick(() => {
              if(this.appendBody){
                let componentController = document.createElement('div');
                componentController.id = this.ajaxId;
                document.body.appendChild(componentController);
              }

              console.log('ajax-component this.ajaxId', this.ajaxId);
              // console.log('ajax-component code', code.replace("createApp({", `createApp({ajaxId:"${this.ajaxId}",`));
              
              $("#" + this.ajaxId).html(code.replace("createApp({", `createApp({ajaxId:"${this.ajaxId}",`))
            })
          },
          error: (err) => {
            
          }
        })
      }
    },
    watch: {
      data: {
        handler(newVal, oldVal) {
          console.log("ajax-component", newVal);
          
          window.$bus.publish(this.ajaxId, newVal, "update-data")
        },
        deep: true
      }
    },
  })
})(window)